package org.fintan.make.service;

import org.fintan.make.dao.UserMapper;
import org.fintan.make.entity.User;
import org.fintan.make.master.ExecuteResult;
import org.fintan.make.params.UserParam;
import org.fintan.make.utils.JWTUtil;
import org.fintan.make.utils.MD5util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class LogInService {
	private JWTUtil jwtUtil;
	@Autowired
	private JedisPool jedisPool;
	@Autowired
	public LogInService(JWTUtil jwtUtil){
		this.jwtUtil = jwtUtil;
	}
	
	
	Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserMapper userMapper;
	
	public ExecuteResult<?> logIn(UserParam param){
		log.info("开始登陆："+param.getUserName());
		User user = userMapper.selectUserByUserName(param.getUserName());
		if(user == null){
			return ExecuteResult.fail("用户不存在");
		}
		String token = "";
		String password = user.getSalt()+param.getPassword();
		if(MD5util.MD5(password).equals(user.getPassword())){
			log.info("登陆成功，用户为："+user.getUserName());
			token = jwtUtil.createJWT(user);
			
			Jedis jediss = jedisPool.getResource();
			jediss.set("user_" + user.getId(), JSON.toJSONString(token));// 放入缓存中
			jediss.close();
			
			return ExecuteResult.ok(token);
		}
		else{
			return ExecuteResult.fail("用户密码错误不存在");
		}
	}
}
